package yc.star.forum.Interceptor;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yc.star.forum.common.Constant;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${forum.login.url}")
    private String loginUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session
        HttpSession session = request.getSession(false);
        // 判断session的有效性
        if (session != null && session.getAttribute(Constant.USER_SESSION) != null) {
            return true;
        }
        // 校验URL是否正确
        if (!loginUrl.startsWith("/")) {
            loginUrl = "/" + loginUrl;
        }
        // 未登录跳转到登录页面
        response.sendRedirect(loginUrl);
        return false;
    }
}